package com.xinqi.modules.user.users.third.manager.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinqi.common.core.utils.DateUtils;
import com.xinqi.common.mybatis.data.service.impl.BaseServiceImpl;
import com.xinqi.modules.user.users.third.domain.UserLoginLogEntity;
import com.xinqi.modules.user.users.third.manager.UserLoginLogManager;
import com.xinqi.modules.user.users.third.mapper.UserLoginLogMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 设备表管理层实现
 *
 * @author: yyzhen
 * @date: 2023/07/17
 */
@Service
@RequiredArgsConstructor
public class UserLoginLogManagerImpl extends BaseServiceImpl<UserLoginLogMapper, UserLoginLogEntity> implements UserLoginLogManager {

    /**
     * 通过用户ID删除
     *
     * @param userId
     */
    @Override
    public void deleteByUserId(Long userId) {
        this.baseMapper.delete(new LambdaQueryWrapper<UserLoginLogEntity>().eq(UserLoginLogEntity::getUserId, userId));
    }

    @Override
    public void generateLog(UserLoginLogEntity log) {
        UserLoginLogEntity info = new UserLoginLogEntity();
        LambdaQueryWrapper<UserLoginLogEntity> logLambdaQueryWrapper = new LambdaQueryWrapper<UserLoginLogEntity>()
            .eq(UserLoginLogEntity::getImei, log.getImei())
            .eq(UserLoginLogEntity::getPsystem, log.getPsystem())
            .eq(UserLoginLogEntity::getType, log.getType())
            .eq(UserLoginLogEntity::getTitle, log.getTitle())
            .eq(UserLoginLogEntity::getUserId, log.getUserId());

        List<UserLoginLogEntity> list = this.list(logLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            List<Long> ids = list.stream().map(UserLoginLogEntity::getId).collect(Collectors.toList());
            this.deletedByIds(ids);
        }
        info.setImei(log.getImei());
        info.setPsystem(log.getPsystem());
        // 判断时苹果手机登录
        if (Objects.nonNull(log.getTitle())) {
            if (log.getTitle().contains("iPad") || log.getTitle().contains("iPhone")) {
                info.setPsystem("IOS");
            }
        }
        info.setTitle(log.getTitle());
        info.setType(log.getType());
        info.setUserId(log.getUserId());
        info.setLastLogin(DateUtils.getNowDateTime());
        this.save(info);
    }

}
